package com.sky.controller.admin;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@RestController
@RequestMapping("/admin/test")
@Slf4j
public class TestController {

    // 设置店铺营业状态
    @PostMapping("/aaa")
    public void test(@RequestBody String temperature) {
        try {
            // 目标URL
            String url = "https://oapi.dingtalk.com/robot/send?access_token=f44ae246cb0cae856809a928b273a411c2b5fb4b891b98ae2b0d9dfdf6889b01";

            // 创建URL对象
            URL obj = new URL(url);
            // 创建HttpURLConnection对象
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为POST
            con.setRequestMethod("POST");

            // 设置请求头
            con.setRequestProperty("Content-Type", "application/json");

            // 构建请求体
            String message = "警告！0号服务器显示：有传感器的温度值超过了阈值！温度为："+temperature.toString();
            JSONObject json = new JSONObject();
            json.put("msgtype", "text");
            JSONObject text = new JSONObject();
            text.put("content", message);
            json.put("text", text);
            String requestBody = json.toString();

            // 启用输出流
            con.setDoOutput(true);
            // 获取输出流
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            // 写入请求体
            wr.write(requestBody.getBytes("UTF-8"));
            wr.flush();
            wr.close();

            // 获取响应码
            int responseCode = con.getResponseCode();
            // 输出响应码
            System.out.println("Response Code : " + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 输出响应内容
            System.out.println("Response Content: " + response.toString());

        } catch (Exception e) {
            // 输出异常信息
            e.printStackTrace();
        }
    }
}